package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class AlbumReceiver {


    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = {MqConst.ROUTING_TRACK_STAT_UPDATE}))
    public void updateAlbumStat(String trackJson, Message message, Channel channel) {
        if (!StringUtils.isEmpty(trackJson)) {
            //传过来的是我们转换好了的JSONString，这里我们需要将jsonStirng转换回javaobject
            TrackStatMqVo trackStatMqVo = JSON.parseObject(trackJson, TrackStatMqVo.class);
            //获取业务编号
            String businessNo = trackStatMqVo.getBusinessNo();
            //根据缓存中获取数据
            Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(businessNo, 1, 30, TimeUnit.SECONDS);
            if (ifAbsent) {
                //进行更新声音的播放量
                try {
                    trackInfoService.updateTrackStat(trackStatMqVo);
                } catch (Exception e) {
                    log.error(e.getMessage());
                    redisTemplate.delete(businessNo);
                }
            }
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
